import React from 'react'
import { renderToString } from 'react-dom/server'
import { StaticRouter } from 'react-router-dom/server'
import { Provider } from 'react-redux'
import { createMemoryRouter, RouterProvider } from 'react-router-dom'
import { createCache, extractStyle, StyleProvider } from '@ant-design/cssinjs'
import store from './store'
import { MemoLogin } from '@/views/Login'
import { MemoRegister } from '@/views/Register'
import 'normalize.css'
import '@/styles/index.less'

// 创建服务端路由配置（包含根路径、登录和注册页）
const createServerRouter = (initialEntries) => {
  return createMemoryRouter([
    {
      path: '/',
      element: <MemoLogin />  // 根路径直接显示登录页面
    },
    {
      path: '/login',
      element: <MemoLogin />
    },
    {
      path: '/register', 
      element: <MemoRegister />
    }
  ], {
    initialEntries,
    initialIndex: 0
  })
}

export function render(url) {
  // 创建样式缓存
  const cache = createCache()
  const router = createServerRouter([url])
  
  const html = renderToString(
    <StyleProvider cache={cache} hashPriority="high">
      <Provider store={store}>
        <RouterProvider router={router} />
      </Provider>
    </StyleProvider>
  )
  
  // 提取样式，确保包含完整的样式信息
  const styles = extractStyle(cache, true)
  
  return { html, styles }
}